package org.september.pisces.led.service;


import org.september.pisces.led.entity.Led;
import org.september.pisces.led.entity.LedFlash;
import org.september.pisces.led.entity.LedPlan;
import lombok.extern.slf4j.Slf4j;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

//情报板发送线程,便于管理
@Slf4j
public class LedThread extends Thread {
    Led led;
    boolean changeFlag = false;
    public void setChangeFlag(boolean changeFlag) {
        this.changeFlag = changeFlag;
    }

    public LedThread(Led led) {
        this.led = led;
    }

    @Override
    public void run() {
        Deque<LedFlash> queue = new LinkedList<>();
        while (!changeFlag) {
            LedPlan plan = led.getPlan();
            List<LedFlash> flashes = plan.getFlashes();
            if (flashes.isEmpty()) {
                log.info(led.getHost() + ",没有要发布的标语");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    log.error("sleep异常1", e);
                }
                continue;
            }
            queue.addAll(flashes);
            int msgCount = 0;
            while (!changeFlag && !queue.isEmpty()) {
                LedFlash flash = queue.remove();// 弹出第一个
                Integer waitTime = flash.getWaitTime();
                led.getManager().showFlash(flash, null);
                msgCount++;
                try {
                    Thread.sleep(waitTime * 1000L);
                } catch (InterruptedException e) {
                    log.error("sleep异常2", e);
                }
            }
            if (msgCount > 0) {
                log.info(led.getHost() + ",发布标语一轮完毕");
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.error("sleep异常3", e);
            }
        }
    }

}
